import NProgress from 'nprogress';
import { Router } from 'vue-router';
import { Storage } from '@/utils/Storage';
import { message } from '@/utils/useMessage';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

export function createRouterGuards(router: Router) {
  // 全局路由前置守卫
  router.beforeEach((to, _from, next) => {
    const token = '4bbdc3bb-2c19-44c0-a148-108b2d78d878';
    // const token = Storage.get('Merchants-Token');
    // 开始进度条
    NProgress.start();
    // 判断是否有token存储
    if (token) {
      if (to.query.token && to.query.token != token) {
        Storage.set('Merchants-Token', to.query.token);
      }
      next();
    } else {
      const getToken = window.location.search.substring(1).split('=');
      // 没有存储token去判断是否是从门户跳转过来
      if (getToken[0] == 'token' && getToken[1]) {
        // 是从综合门户跳转过来
        Storage.set('Merchants-Token', getToken[1]);
        next();
      } else {
        // 不是从综合门户跳转过来，跳转到处理页面
        message.error('请统一通过奉化经济智治平台进入');
        // window.open('http://testfhjjzl.zjrongxiang.com/#/login', '_self');
        // window.open(window.VITE_PAGE_URL + '#/login', '_self');
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });

  router.onError((error) => {
    console.log(error, '路由错误');
  });
}
